package auth

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"time"
	"wms/model"
	"wms/pkg/cryptx"
	"wms/pkg/jwtx"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
	resp = new(types.LoginResponse)

	const userTokenKey = "token:user:%d"

	//1.账号是否存在
	user, err := l.svcCtx.UserModel.FindOneByName(l.ctx, strings.TrimSpace(req.Name))
	switch err {
	case nil:
	case model.ErrNotFound:
		fmt.Printf("[Error]账号[%s]不存在\n", req.Name)
		resp.Code = http.StatusBadRequest
		resp.Msg = "账号不存在"
		return resp, nil
	default:
		fmt.Printf("[Error]查询账号[%s]信息:%s\n", req.Name, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.密码校验
	if user.Password != cryptx.PasswordEncrypt(l.svcCtx.Config.Salt, strings.TrimSpace(req.Password)) {
		resp.Code = http.StatusBadRequest
		resp.Msg = "密码错误"
		return resp, nil
	}

	if user.Status == 0 {
		resp.Code = http.StatusBadRequest
		resp.Msg = "用户已禁用"
		return resp, nil
	}

	//3.更新token
	now := time.Now()
	token, err := jwtx.GetToken(l.svcCtx.Config.Auth.AccessSecret, user.Id, now.Unix(), l.svcCtx.Config.Auth.AccessExpire)
	if err != nil {
		fmt.Printf("[Error]账号[%d]生成token:%s\n", user.Id, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	err = l.svcCtx.Cache.SetWithExpireCtx(l.ctx, fmt.Sprintf(userTokenKey, user.Id), token, time.Duration(l.svcCtx.Config.Auth.AccessExpire))
	if err != nil {
		fmt.Printf("[Error]缓存用户[%d]Token:%s\n", user.Id, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	resp.Data.Mobile = user.Mobile
	resp.Data.Token = token
	resp.Data.Exp = now.Unix() + l.svcCtx.Config.Auth.AccessExpire
	return resp, nil
}
